home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / share / hplip / hpssd.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-10-28  |  15KB  |  423 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __version__ = '12.0'
  5. __title__ = 'Services and Status System Tray dBus Child/Parent Process'
  6. __mod__ = 'hpssd'
  7. __doc__ = 'Provides persistent data and event services to HPLIP client applications. Required to be running for PC send fax, optional in all other cases.'
  8. import sys
  9. import struct
  10. import os
  11. import time
  12. import getopt
  13. import select
  14. import signal
  15. import tempfile
  16. from cPickle import loads, HIGHEST_PROTOCOL
  17. from base.g import *
  18. from base.codes import *
  19. from base import utils, device, status, models
  20.  
  21. try:
  22.     from dbus import lowlevel, SystemBus, SessionBus
  23.     import dbus.service as dbus
  24.     from dbus.mainloop.glib import DBusGMainLoop
  25.     from gobject import MainLoop, timeout_add, threads_init, io_add_watch, IO_IN
  26.     dbus_loaded = True
  27. except ImportError:
  28.     log.error('dbus failed to load (python-dbus ver. 0.80+ required). Exiting...')
  29.     dbus_loaded = False
  30.     sys.exit(1)
  31.  
  32. import warnings
  33. warnings.simplefilter('ignore', DeprecationWarning)
  34. PIPE_BUF = 4096
  35. (dbus_loop, main_loop) = (None, None)
  36. system_bus = None
  37. session_bus = None
  38. (w1, w2, r3) = (None, None, None)
  39. devices = { }
  40.  
  41. class DeviceCache(object):
  42.     
  43.     def __init__(self, model = ''):
  44.         self.history = utils.RingBuffer(prop.history_size)
  45.         self.model = models.normalizeModelName(model)
  46.         self.cache = { }
  47.         self.faxes = { }
  48.         self.dq = { }
  49.         self.backoff_counter = 0
  50.         self.backoff_countdown = 0
  51.         self.polling = False
  52.  
  53.  
  54.  
  55. class StatusService(dbus.service.Object):
  56.     
  57.     def __init__(self, name, object_path):
  58.         dbus.service.Object.__init__(self, name, object_path)
  59.  
  60.     
  61.     def GetHistory(self, device_uri):
  62.         log.debug("GetHistory('%s')" % device_uri)
  63.         send_systray_blip()
  64.         
  65.         try:
  66.             devices[device_uri]
  67.         except KeyError:
  68.             return (device_uri, [])
  69.  
  70.         h = devices[device_uri].history.get()
  71.         log.debug('%d events in history:' % len(h))
  72.         [ x.debug() for x in h ]
  73.         return ([], [ x.as_tuple() for x in h ])
  74.  
  75.     GetHistory = dbus.service.method('com.hplip.StatusService', in_signature = 's', out_signature = 'sa(ssisisd)')(GetHistory)
  76.     
  77.     def GetStatus(self, device_uri):
  78.         log.debug("GetStatus('%s')" % device_uri)
  79.         send_systray_blip()
  80.         
  81.         try:
  82.             devices[device_uri]
  83.         except KeyError:
  84.             return (device_uri, { })
  85.  
  86.         t = { }
  87.         dq = devices[device_uri].dq
  88.         [ t.setdefault(x, str(dq[x])) for x in dq.keys() ]
  89.         log.debug(t)
  90.         return (device_uri, t)
  91.  
  92.     GetStatus = dbus.service.method('com.hplip.StatusService', in_signature = 's', out_signature = 'sa{ss}')(GetStatus)
  93.     
  94.     def SetCachedIntValue(self, device_uri, key, value):
  95.         log.debug("SetCachedIntValue('%s', '%s', %d)" % (device_uri, key, value))
  96.         if check_device(device_uri) == ERROR_SUCCESS:
  97.             devices[device_uri].cache[key] = value
  98.             return value
  99.         return -1
  100.  
  101.     SetCachedIntValue = dbus.service.method('com.hplip.StatusService', in_signature = 'ssi', out_signature = 'i')(SetCachedIntValue)
  102.     
  103.     def GetCachedIntValue(self, device_uri, key):
  104.         
  105.         try:
  106.             ret = devices[device_uri].cache[key]
  107.         except KeyError:
  108.             ret = -1
  109.  
  110.         log.debug("GetCachedIntValue('%s', '%s') --> %d" % (device_uri, key, ret))
  111.         return ret
  112.  
  113.     GetCachedIntValue = dbus.service.method('com.hplip.StatusService', in_signature = 'ss', out_signature = 'i')(GetCachedIntValue)
  114.     
  115.     def SetCachedStrValue(self, device_uri, key, value):
  116.         log.debug("SetCachedStrValue('%s', '%s', '%s')" % (device_uri, key, value))
  117.         if check_device(device_uri) == ERROR_SUCCESS:
  118.             devices[device_uri].cache[key] = value
  119.             return value
  120.         return ''
  121.  
  122.     SetCachedStrValue = dbus.service.method('com.hplip.StatusService', in_signature = 'sss', out_signature = 's')(SetCachedStrValue)
  123.     
  124.     def GetCachedStrValue(self, device_uri, key):
  125.         
  126.         try:
  127.             ret = devices[device_uri].cache[key]
  128.         except KeyError:
  129.             ret = ''
  130.  
  131.         log.debug("GetCachedStrValue('%s', '%s') --> %s" % (device_uri, key, ret))
  132.         return ret
  133.  
  134.     GetCachedStrValue = dbus.service.method('com.hplip.StatusService', in_signature = 'ss', out_signature = 's')(GetCachedStrValue)
  135.     
  136.     def CheckForWaitingFax(self, device_uri, username, job_id = 0):
  137.         log.debug("CheckForWaitingFax('%s', '%s', %d)" % (device_uri, username, job_id))
  138.         send_systray_blip()
  139.         r = (device_uri, '', 0, username, job_id, '', 0, '')
  140.         check_device(device_uri)
  141.         show_waiting_faxes(device_uri)
  142.         if job_id:
  143.             
  144.             try:
  145.                 devices[device_uri].faxes[(username, job_id)]
  146.             except KeyError:
  147.                 return r
  148.  
  149.             return self.check_for_waiting_fax_return(device_uri, username, job_id)
  150.         job_id
  151.         for u, j in devices[device_uri].faxes.keys():
  152.             if u == username:
  153.                 return self.check_for_waiting_fax_return(device_uri, u, j)
  154.         
  155.         return r
  156.  
  157.     CheckForWaitingFax = dbus.service.method('com.hplip.StatusService', in_signature = 'ssi', out_signature = 'ssisisds')(CheckForWaitingFax)
  158.     
  159.     def check_for_waiting_fax_return(self, d, u, j):
  160.         log.debug('Fax (username=%s, jobid=%d) removed from faxes and returned to caller.' % (u, j))
  161.         r = devices[d].faxes[(u, j)].as_tuple()
  162.         del devices[d].faxes[(u, j)]
  163.         show_waiting_faxes(d)
  164.         return r
  165.  
  166.     
  167.     def SendEvent(self, device_uri, printer_name, event_code, username, job_id, title):
  168.         event = device.Event(device_uri, printer_name, event_code, username, job_id, title)
  169.         handle_event(event)
  170.  
  171.     SendEvent = dbus.service.method('com.hplip.StatusService', in_signature = 'ssisis', out_signature = '')(SendEvent)
  172.  
  173.  
  174. def check_device(device_uri):
  175.     
  176.     try:
  177.         devices[device_uri]
  178.     except KeyError:
  179.         log.debug('New device: %s' % device_uri)
  180.         
  181.         try:
  182.             (back_end, is_hp, bus, model, serial, dev_file, host, zc, port) = device.parseDeviceURI(device_uri)
  183.         except Error:
  184.             log.debug('Invalid device URI: %s' % device_uri)
  185.             return ERROR_INVALID_DEVICE_URI
  186.  
  187.         devices[device_uri] = DeviceCache(model)
  188.  
  189.     return ERROR_SUCCESS
  190.  
  191.  
  192. def create_history(event):
  193.     history = devices[event.device_uri].history.get()
  194.     if history and history[-1].event_code == event.event_code:
  195.         log.debug('Duplicate event. Replacing previous event.')
  196.         devices[event.device_uri].history.replace(event)
  197.         return True
  198.     devices[event.device_uri].history.append(event)
  199.     return False
  200.  
  201.  
  202. def handle_fax_event(event, pipe_name):
  203.     if event.event_code == EVENT_FAX_RENDER_COMPLETE and event.username == prop.username:
  204.         (fax_file_fd, fax_file_name) = tempfile.mkstemp(prefix = 'hpfax-')
  205.         pipe = os.open(pipe_name, os.O_RDONLY)
  206.         bytes_read = 0
  207.         while True:
  208.             data = os.read(pipe, PIPE_BUF)
  209.             if not data:
  210.                 break
  211.             
  212.             os.write(fax_file_fd, data)
  213.             bytes_read += len(data)
  214.         log.debug('Saved %d bytes to file %s' % (bytes_read, fax_file_name))
  215.         os.close(pipe)
  216.         os.close(fax_file_fd)
  217.         devices[event.device_uri].faxes[(event.username, event.job_id)] = device.FaxEvent(fax_file_name, event)
  218.         show_waiting_faxes(event.device_uri)
  219.         
  220.         try:
  221.             os.waitpid(-1, os.WNOHANG)
  222.         except OSError:
  223.             pass
  224.  
  225.         (ok, lock_file) = utils.lock_app('hp-sendfax-%s' % event.printer_name, True)
  226.         if ok:
  227.             utils.unlock(lock_file)
  228.             path = utils.which('hp-sendfax')
  229.             if path:
  230.                 path = os.path.join(path, 'hp-sendfax')
  231.             else:
  232.                 log.error('Unable to find hp-sendfax on PATH.')
  233.                 return None
  234.             path.debug('Running hp-sendfax: %s --printer=%s' % (path, event.printer_name))
  235.             os.spawnlp(os.P_NOWAIT, path, 'hp-sendfax', '--printer=%s' % event.printer_name)
  236.         else:
  237.             log.debug('hp-sendfax is running. Waiting for CheckForWaitingFax() call.')
  238.     else:
  239.         log.warn('Not handled!')
  240.  
  241.  
  242. def show_waiting_faxes(d):
  243.     f = devices[d].faxes
  244.     if not len(f):
  245.         log.debug('No faxes waiting for %s' % d)
  246.     elif len(f) == 1:
  247.         log.debug('1 fax waiting for %s:' % d)
  248.     else:
  249.         log.debug('%d faxes waiting for %s:' % (len(f), d))
  250.     [ f[x].debug() for x in f ]
  251.  
  252.  
  253. def handle_hpdio_event(event, bytes_written):
  254.     log.debug('Reading %d bytes from hpdio pipe...' % bytes_written)
  255.     (total_read, data) = (0, '')
  256.     while True:
  257.         (r, w, e) = select.select([
  258.             r3], [], [
  259.             r3], 0)
  260.         if not r:
  261.             break
  262.         
  263.         x = os.read(r3, PIPE_BUF)
  264.         if not x:
  265.             break
  266.         
  267.         data = ''.join([
  268.             data,
  269.             x])
  270.         total_read += len(x)
  271.         if total_read == bytes_written:
  272.             break
  273.             continue
  274.     log.debug('Read %d bytes' % total_read)
  275.     if total_read == bytes_written:
  276.         dq = loads(data)
  277.         if check_device(event.device_uri) == ERROR_SUCCESS:
  278.             devices[event.device_uri].dq = dq.copy()
  279.             handle_event(device.Event(event.device_uri, '', dq.get('status-code', STATUS_PRINTER_IDLE), prop.username, 0, ''))
  280.             send_toolbox_event(event, EVENT_DEVICE_UPDATE_REPLY)
  281.         
  282.     
  283.  
  284.  
  285. def handle_event(event, more_args = None):
  286.     log.debug('Handling event...')
  287.     if more_args is None:
  288.         more_args = []
  289.     
  290.     event.debug()
  291.     if event.device_uri and check_device(event.device_uri) != ERROR_SUCCESS:
  292.         return None
  293.     if event.event_code > EVENT_MAX_EVENT:
  294.         event.event_code = status.MapPJLErrorCode(event.event_code)
  295.     
  296.     if event.event_code < EVENT_MIN_USER_EVENT:
  297.         pass
  298.     elif event.event_code <= event.event_code:
  299.         pass
  300.     elif event.event_code <= EVENT_MAX_USER_EVENT:
  301.         if event.device_uri:
  302.             dup_event = create_history(event)
  303.             if event.event_code in (EVENT_DEVICE_STOP_POLLING, EVENT_START_MAINT_JOB, EVENT_START_COPY_JOB, EVENT_START_FAX_JOB, EVENT_START_PRINT_JOB):
  304.                 pass
  305.             elif event.event_code in (EVENT_DEVICE_START_POLLING, EVENT_END_MAINT_JOB, EVENT_END_COPY_JOB, EVENT_END_FAX_JOB, EVENT_END_PRINT_JOB, EVENT_PRINT_FAILED_MISSING_PLUGIN, EVENT_SCANNER_FAIL, EVENT_END_SCAN_JOB, EVENT_SCAN_FAILED_MISSING_PLUGIN, EVENT_FAX_JOB_FAIL, EVENT_FAX_JOB_CANCELED, EVENT_FAX_FAILED_MISSING_PLUGIN, EVENT_COPY_JOB_FAIL, EVENT_COPY_JOB_CANCELED):
  306.                 pass
  307.             
  308.         
  309.         if not dup_event:
  310.             send_event_to_systray_ui(event)
  311.         
  312.         send_toolbox_event(event, EVENT_HISTORY_UPDATE)
  313.     elif event.event_code <= event.event_code:
  314.         pass
  315.     elif event.event_code <= EVENT_FAX_MAX and more_args:
  316.         log.debug('Fax event')
  317.         pipe_name = str(more_args[0])
  318.         handle_fax_event(event, pipe_name)
  319.     elif event.event_code == EVENT_USER_CONFIGURATION_CHANGED:
  320.         send_event_to_systray_ui(event)
  321.     elif event.event_code == EVENT_SYS_CONFIGURATION_CHANGED:
  322.         send_event_to_systray_ui(event)
  323.     elif event.event_code in (EVENT_DEVICE_UPDATE_REQUESTED,):
  324.         send_event_to_hpdio(event)
  325.     elif event.event_code in (EVENT_DEVICE_UPDATE_ACTIVE, EVENT_DEVICE_UPDATE_INACTIVE):
  326.         send_event_to_systray_ui(event)
  327.     elif event.event_code == EVENT_DEVICE_UPDATE_REPLY:
  328.         bytes_written = int(more_args[1])
  329.         handle_hpdio_event(event, bytes_written)
  330.     elif event.event_code == EVENT_SYSTEMTRAY_EXIT:
  331.         send_event_to_hpdio(event)
  332.         send_toolbox_event(event)
  333.         send_event_to_systray_ui(event)
  334.         log.debug('Exiting')
  335.         main_loop.quit()
  336.     elif event.event_code in (EVENT_DEVICE_START_POLLING, EVENT_DEVICE_STOP_POLLING):
  337.         pass
  338.     else:
  339.         log.error('Unhandled event: %d' % event.event_code)
  340.  
  341.  
  342. def send_systray_blip():
  343.     send_event_to_systray_ui(device.Event('', '', EVENT_DEVICE_UPDATE_BLIP))
  344.  
  345.  
  346. def send_event_to_systray_ui(event, event_code = None):
  347.     e = event.copy()
  348.     if event_code is not None:
  349.         e.event_code = event_code
  350.     
  351.     e.send_via_pipe(w1, 'systemtray')
  352.  
  353.  
  354. def send_event_to_hpdio(event):
  355.     event.send_via_pipe(w2, 'hpdio')
  356.  
  357.  
  358. def send_toolbox_event(event, event_code = None):
  359.     e = event.copy()
  360.     if event_code is not None:
  361.         e.event_code = event_code
  362.     
  363.     e.send_via_dbus(session_bus, 'com.hplip.Toolbox')
  364.  
  365.  
  366. def handle_signal(typ, *args, **kwds):
  367.     if kwds['interface'] == 'com.hplip.StatusService' and kwds['member'] == 'Event':
  368.         event = device.Event(*args[:6])
  369.         return handle_event(event, args[6:])
  370.  
  371.  
  372. def handle_system_signal(*args, **kwds):
  373.     return handle_signal('system', *args, **kwds)
  374.  
  375.  
  376. def handle_session_signal(*args, **kwds):
  377.     return handle_signal('session', *args, **kwds)
  378.  
  379.  
  380. def run(write_pipe1 = None, write_pipe2 = None, read_pipe3 = None):
  381.     global w1, w2, r3, dbus_loop, main_loop, system_bus, session_bus
  382.     log.set_module('hp-systray(hpssd)')
  383.     log.debug('PID=%d' % os.getpid())
  384.     w1 = write_pipe1
  385.     w2 = write_pipe2
  386.     r3 = read_pipe3
  387.     dbus_loop = DBusGMainLoop(set_as_default = True)
  388.     main_loop = MainLoop()
  389.     
  390.     try:
  391.         system_bus = SystemBus(mainloop = dbus_loop)
  392.     except dbus.exceptions.DBusException:
  393.         e = None
  394.         log.error('Unable to connect to dbus system bus. Exiting.')
  395.         sys.exit(1)
  396.  
  397.     
  398.     try:
  399.         session_bus = dbus.SessionBus()
  400.     except dbus.exceptions.DBusException:
  401.         e = None
  402.         if os.getuid() != 0:
  403.             log.error('Unable to connect to dbus session bus. Exiting.')
  404.             sys.exit(1)
  405.         else:
  406.             log.error('Unable to connect to dbus session bus (running as root?)')
  407.             sys.exit(1)
  408.     except:
  409.         os.getuid() != 0
  410.  
  411.     system_bus.add_signal_receiver(handle_system_signal, sender_keyword = 'sender', destination_keyword = 'dest', interface_keyword = 'interface', member_keyword = 'member', path_keyword = 'path')
  412.     session_bus.add_signal_receiver(handle_session_signal, sender_keyword = 'sender', destination_keyword = 'dest', interface_keyword = 'interface', member_keyword = 'member', path_keyword = 'path')
  413.     session_name = dbus.service.BusName('com.hplip.StatusService', session_bus)
  414.     status_service = StatusService(session_name, '/com/hplip/StatusService')
  415.     log.debug('Entering main dbus loop...')
  416.     
  417.     try:
  418.         main_loop.run()
  419.     except KeyboardInterrupt:
  420.         log.debug('Ctrl-C: Exiting...')
  421.  
  422.  
  423.